package com.polelink.testcenter.converter;

import com.opencsv.CSVReader;
import com.polelink.testcenter.dto.DtcDto;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;


@Slf4j
public class DTCToIniConverter {

    public static void parse(String dtcPath, String baseDir) throws Exception {
        String inputFileName = new File(dtcPath).getName().replaceFirst("\\.[^.]+$", ".ini");
        String iniFilePath = baseDir + File.separator + "dtc" + File.separator + inputFileName;
        // 新增目录创建逻辑
        new File(iniFilePath).getParentFile().mkdirs();

        List<DtcDto> dtcEntries = readCsv(dtcPath);
        long writeStart = System.nanoTime();
        generateOptimizedIni(dtcEntries, iniFilePath);
        long writeCost = System.nanoTime() - writeStart;
        String successMessage = String.format("DTC_INI生成耗时：%.3fms", writeCost / 1e6);
        log.info(successMessage);

    }

    private static void generateOptimizedIni(List<DtcDto> dtcEntries, String outputPath) throws IOException {
        // 预设StringBuilder容量(根据经验值)
        StringBuilder sb = new StringBuilder(dtcEntries.size());
        sb.append("#DTC信息\n").append("[").append(dtcEntries.get(0).getFileName().replace(".csv","")).append("]\n");
        dtcEntries.forEach(entry ->
                sb.append(entry.getCode()).append(" = ").append(entry.getDescription()).append("\n")
        );
        OutputStreamWriter os = new OutputStreamWriter(Files.newOutputStream(Paths.get(outputPath)), Charset.forName("GBK"));
        os.write(sb.toString());
    }


    private static List<DtcDto> readCsv(String csvFilePath) throws Exception {
        List<DtcDto> entries = new ArrayList<>();
        String fileName = new File(csvFilePath).getName();
        try (CSVReader reader = new CSVReader(new InputStreamReader(Files.newInputStream(Paths.get(csvFilePath)), Charset.forName("GBK")))) {
            String[] nextLine;
            // 跳过标题行
            reader.readNext();
            while ((nextLine = reader.readNext()) != null) {
                if (nextLine.length >= 2) {
                    // 修正为使用ICommonsList的get方法
                    String dtc = nextLine[0] != null ? nextLine[0].trim() : "";
                    String description = nextLine[1] != null ? nextLine[1].trim() : "";
                    try {
                        if (dtc.length() != 7) {
                            continue;
                        }
                        long code = convertDtcToCode(dtc);
                        entries.add(new DtcDto(fileName, code, description));
                    } catch (IllegalArgumentException e) {
                        System.err.println("无效的DTC代码格式: " + dtc + "，错误: " + e.getMessage());
                    }
                }
            }
        }
        return entries;
    }

    private static long convertDtcToCode(String dtc) {
        char prefix = dtc.charAt(0);
        String codePart = dtc.substring(2);
        if (!codePart.matches("[0-9A-Fa-f]{5}")) {
            throw new IllegalArgumentException("DTC后五位为十六进制数字");
        }
        long offset = switch (Character.toUpperCase(prefix)) {
            case 'P' -> 0x0000L;
            case 'C' -> 0x4000L;
            case 'B' -> 0x8000L;
            case 'U' -> 0xC000L;
            default -> throw new IllegalArgumentException("无效的前缀: " + prefix);
        };
        return offset + Long.parseLong(codePart, 16);
    }

}